from coreServices.models import ChatRecord
from userServer.models import UserInfo
from django.core.exceptions import ObjectDoesNotExist

# \userServer\dao\ChatRecordDao.py
#用户提交时调用存储聊天记录
def save_chat_record(user_id, input_text, output_text):
    try:
        # 获取 UserInfo 实例
        user_info = UserInfo.objects.get(id=user_id)

        # 确保 input_text 和 output_text 是字符串
        if not isinstance(input_text, str):
            print(f"input_text is not a string: {input_text}")
            input_text = str(input_text)

        if not isinstance(output_text, str):
            print(f"output_text is not a string: {output_text}")
            output_text = str(output_text)

        # 创建并保存 ChatRecord 实例
        chatRecord = ChatRecord(userId=user_info, chat_content=input_text, reply_content=output_text)
        chatRecord.save()
    except ObjectDoesNotExist:
        # 处理 UserInfo 实例不存在的情况
        print(f"UserInfo with id {user_id} does not exist.")
        # 或者记录日志，抛出自定义异常等
    except Exception as e:
        # 捕获其他异常并打印错误信息
        print(f"An error occurred: {e}")

#获取聊天记录
def get_chat_record(user_id):
    """获取聊天记录"""
    #TODO: 从数据库中获取聊天记录
    chatRecord = ChatRecord.objects.filter(userId=user_id)
    return chatRecord
